import { ElLoading, ElMessage } from "element-plus";
import request from "./index";
import { handleUnauthorized } from "@/api/utils/auth";

export const download = (
  url: string,
  params: any,
  fileName: string,
  config: any = {}
) => {
  const downloadLoading = ElLoading.service({
    lock: true,
    text: "正在下载...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  return request
    .post(url, params, {
      ...config,
      responseType: "blob",
    })
    .then((res) => {
      const blob = new Blob([res.data]);

      // 尝试判断是否是错误响应（JSON）
      const contentType = res.headers["content-type"];
      if (
        contentType &&
        (contentType.includes("application/json") ||
          contentType.includes("text/plain"))
      ) {
        const fileReader = new FileReader();
        fileReader.readAsText(blob);
        fileReader.onload = () => {
          try {
            const result = JSON.parse(fileReader.result as string);
            if (result.code === 401) {
              handleUnauthorized();
            } else {
              ElMessage.error(result.msg || "下载返回错误");
            }
          } catch {
            ElMessage.error("解析文件失败");
          } finally {
            downloadLoading.close();
          }
        };
        return;
      }

      // 正常文件流处理
      const link = document.createElement("a");
      link.href = window.URL.createObjectURL(blob);
      link.download = fileName;
      link.click();
      downloadLoading.close();
    })
    .catch((error) => {
      console.error(error);
      ElMessage.error("下载失败，请联系管理员");
      downloadLoading.close();
      return Promise.reject(error);
    });
};
